package william.tree;

/**
 * @author ZhangShenao
 * @date 2024/3/20
 * @description <a href="https://leetcode.cn/problems/path-sum/description/">...</a>
 */
public class Leetcode112_路径总和 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 采用全局变量,记录是否已经找到路径和
     */
    private boolean found = false;

    /**
     * 采用递归算法
     * 采用全局变量,记录是否已经找到路径和
     * 针对当前节点进行判断:
     * -如果已经找到路径和,则直接返回true,减少重复计算
     * -如果当前节点是叶子节点,则判断当前节点值是否==sum
     * -递归处理左、右子树,判断路径和是否==sum-当前节点值
     */
    public boolean hasPathSum(TreeNode root, int targetSum) {
        //边界条件校验
        if (root == null) {
            return false;
        }

        //已经找到路径和,直接返回true,减少重复计算
        if (found) {
            return true;
        }

        //如果当前节点是叶子节点,则判断当前节点值是否==sum
        if (root.left == null && root.right == null && root.val == targetSum) {
            return true;
        }

        //递归处理左、右子树,判断路径和是否==sum-当前节点值
        int remains = targetSum - root.val;
        found = (hasPathSum(root.left, remains) || hasPathSum(root.right, remains));
        return found;
    }
}
